package com.atguigu.eduService.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduService.entity.EduSubject;
import com.atguigu.eduService.entity.excel.SubjectData;
import com.atguigu.eduService.entity.subject.OneSubject;
import com.atguigu.eduService.listener.SubjectExcelListener;
import com.atguigu.eduService.mapper.EduSubjectMapper;
import com.atguigu.eduService.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author smday
 * @since 2020-07-27
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Resource
    private EduSubjectMapper mapper;

    /**
     * 添加课程分类
     * @param file excel文件
     */
    @Override
    public void add(MultipartFile file,EduSubjectService eduSubjectService) {
        try{
            //创建文件输入流
            InputStream in = file.getInputStream();
            SubjectExcelListener listener = new SubjectExcelListener(eduSubjectService);
            //读取
            EasyExcel.read(in, SubjectData.class,listener).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 课程分类列表
     * @return 课程分类列表树形
     */
    @Override
    public List<OneSubject> getAllSubjects() {
        //查出所有的subjects
        List<EduSubject> eduSubjects = mapper.selectList(null);
        return getSubjectsByParentId(eduSubjects,"0");


    }

    private List<OneSubject> getSubjectsByParentId(List<EduSubject> eduSubjects,String pid){
        List<OneSubject> list = new ArrayList<>();
        for (EduSubject eduSubject : eduSubjects) {

            if(pid.equals(eduSubject.getParentId())){
                OneSubject oneSubject = new OneSubject();
                BeanUtils.copyProperties(eduSubject,oneSubject);
                oneSubject.setChildren(getSubjectsByParentId(eduSubjects,eduSubject.getId()));
                list.add(oneSubject);
            }
        }
        return list;

    }
}
